//
//  JMVersionUpdateView.m
//  SYPerfectDemo
//
//  Created by Lssyyy on 2019/7/29.
//  Copyright © 2019年 Lssyyy. All rights reserved.
//

#import "JMVersionUpdateView.h"

#define DescriptionFont 13
#define AnimationTimeInterval .6f

//屏幕适配
/**当前设备对应375的比例*/
#define Ratio_375 (UI_SCREEN_WIDTH/375.0)
/**转换成当前比例的数*/
#define Ratio(x) ((int)((x) * Ratio_375))
#define DEFAULT_MAX_HEIGHT UI_SCREEN_HEIGHT/3*2


@interface JMVersionUpdateView()

/** 版本号 */
@property (nonatomic, copy) NSString *version;
/** 版本更新内容 */
@property (nonatomic, copy) NSString *desc;

@end
@implementation JMVersionUpdateView


/**
 添加版本更新提示
 
 @param version 版本号
 @param descriptions 版本更新内容（数组）
 
 descriptions 格式如 @[@"1.xxxxxx",@"2.xxxxxx"]
 */
+ (void)showUpdateAlertWithVersion:(NSString *)version Descriptions:(NSArray *)descriptions
{
    if (!descriptions || descriptions.count == 0) {
        return;
    }
    
    //数组转换字符串，动态添加换行符\n
    NSString *description = @"";
    for (NSInteger i = 0;  i < descriptions.count; ++i) {
        id desc = descriptions[i];
        if (![desc isKindOfClass:[NSString class]]) {
            return;
        }
        description = [description stringByAppendingString:desc];
        if (i != descriptions.count-1) {
            description = [description stringByAppendingString:@"\n"];
        }
    }
    NSLog(@"====%@",description);
    JMVersionUpdateView *updateAlert = [[JMVersionUpdateView alloc]initVersion:version description:description];
    [[UIApplication sharedApplication].delegate.window addSubview:updateAlert];
}

/**
 添加版本更新提示
 
 @param version 版本号
 @param description 版本更新内容（字符串）
 
 description 格式如 @"1.xxxxxx\n2.xxxxxx"
 */
+ (void)showUpdateAlertWithVersion:(NSString *)version Description:(NSString *)description
{
    JMVersionUpdateView *updateAlert = [[JMVersionUpdateView alloc]initVersion:version description:description];
    [[UIApplication sharedApplication].delegate.window addSubview:updateAlert];
}

- (instancetype)initVersion:(NSString *)version description:(NSString *)description
{
    self = [super init];
    if (self) {
        self.version = version;
        self.desc = description;
        
        [self _setupUI];
    }
    return self;
}

- (void)_setupUI{
    self.frame = [UIScreen mainScreen].bounds;
    self.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.4];
    
    //获取更新内容高度
    CGFloat descHeight = [self _sizeofString:self.desc font:[UIFont systemFontOfSize:DescriptionFont] maxSize:CGSizeMake(self.frame.size.width - Ratio(80) - Ratio(56), 1000)].height;
    
    //bgView实际高度
    CGFloat realHeight = descHeight + Ratio(290);
    
    //bgView最大高度
    CGFloat maxHeight = DEFAULT_MAX_HEIGHT;
    //更新内容可否滑动显示
    BOOL scrollEnabled = NO;
    
    //重置bgView最大高度 设置更新内容可否滑动显示
    if (realHeight > DEFAULT_MAX_HEIGHT) {
        scrollEnabled = YES;
        descHeight = DEFAULT_MAX_HEIGHT - Ratio(290);
    }else
    {
        maxHeight = realHeight;
    }
    
    //backgroundView
    UIView *bgView = [[UIView alloc]init];
    bgView.center = self.center;
    bgView.bounds = CGRectMake(0, 0, self.frame.size.width - Ratio(40), maxHeight+Ratio(18));
    [self addSubview:bgView];
    
    //添加更新提示
    UIView *updateView = [[UIView alloc]initWithFrame:CGRectMake(Ratio(20), Ratio(18), bgView.frame.size.width - Ratio(40), maxHeight)];
    updateView.backgroundColor = [UIColor whiteColor];
    updateView.layer.masksToBounds = YES;
    updateView.layer.cornerRadius = 5.0f;
    [bgView addSubview:updateView];
    
    
    UIImageView *updateIcon = [[UIImageView alloc]initWithFrame:CGRectMake((updateView.frame.size.width - Ratio(206))/2, Ratio(26), Ratio(206), Ratio(157))];
    updateIcon.image = [UIImage imageNamed:@"icon_versionupdate"];
    [updateView addSubview:updateIcon];
    
    //版本更新啦
    UILabel *updateTitleLabel = [[UILabel alloc]init];
    updateTitleLabel.text = JMLocalStr(@"版本更新啦");
    updateTitleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:12];
    updateTitleLabel.textColor = [UIColor colorWithRed:40/255.0 green:40/255.0 blue:40/255.0 alpha:1.0];
    CGFloat updateTitleWidth = [self _sizeofString:updateTitleLabel.text font:updateTitleLabel.font maxSize:CGSizeMake(updateView.frame.size.width/2, 13)].width;
    updateTitleLabel.frame = CGRectMake(updateView.frame.size.width/2 - updateTitleWidth, CGRectGetMaxY(updateIcon.frame), updateTitleWidth, 13);
    [updateView addSubview:updateTitleLabel];
    
    //版本号
    UILabel *versionLabel = [[UILabel alloc]init];
    versionLabel.font = [UIFont systemFontOfSize:10];
    versionLabel.textColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0];
    versionLabel.textAlignment = NSTextAlignmentCenter;
    versionLabel.backgroundColor = [UIColor colorWithRed:121/255.0 green:214/255.0 blue:50/255.0 alpha:1.0];
    versionLabel.text = [NSString stringWithFormat:@"V%@",self.version];
    CGFloat versionWidth = [self _sizeofString:versionLabel.text font:versionLabel.font maxSize:CGSizeMake(updateView.frame.size.width/2, 14)].width;
    versionLabel.frame = CGRectMake(CGRectGetMaxX(updateTitleLabel.frame)+10, CGRectGetCenter(updateTitleLabel.frame).y-7, versionWidth+10, 14);
    versionLabel.layer.cornerRadius = 3.0;
    versionLabel.layer.masksToBounds = YES;
    [updateView addSubview:versionLabel];
    
    //更新内容
    UITextView *descTextView = [[UITextView alloc]initWithFrame:CGRectMake(Ratio(28), Ratio(20) + CGRectGetMaxY(versionLabel.frame), updateView.frame.size.width - Ratio(56), descHeight)];
    descTextView.font = [UIFont systemFontOfSize:DescriptionFont];
    descTextView.textContainer.lineFragmentPadding = 0;
    descTextView.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);
    descTextView.text = self.desc;
    descTextView.editable = NO;
    descTextView.selectable = NO;
    descTextView.scrollEnabled = scrollEnabled;
    descTextView.showsVerticalScrollIndicator = scrollEnabled;
    descTextView.showsHorizontalScrollIndicator = NO;
    [updateView addSubview:descTextView];
    if (scrollEnabled) {
        //若显示滑动条，提示可以有滑动条
        [descTextView flashScrollIndicators];
    }
    //分割线
    //水平线
    UIView *horizontalLine = [UIView new];
    horizontalLine.frame = CGRectMake(15,CGRectGetMaxY(descTextView.frame)+Ratio(28), updateView.frame.size.width-30, 1);
    horizontalLine.backgroundColor = [UIColor colorWithRed:234/255.0 green:234/255.0 blue:234/255.0 alpha:1.0];
    [updateView addSubview:horizontalLine];
    
    
    //垂直线
    UIView *verticalityLine = [UIView new];
    verticalityLine.frame = CGRectMake(updateView.frame.size.width/2 -0.5,CGRectGetMaxY(horizontalLine.frame)+10,1,Ratio(30));
    verticalityLine.backgroundColor = [UIColor colorWithRed:234/255.0 green:234/255.0 blue:234/255.0 alpha:1.0];
    [updateView addSubview:verticalityLine];
    
    //取消按钮
    UIButton *cancelButton = [UIButton buttonWithType:0];
    cancelButton.frame = CGRectMake(0,CGRectGetMaxY(horizontalLine.frame),verticalityLine.frame.origin.x,Ratio(50));
    [cancelButton setTitle:JMLocalStr(@"稍后再说") forState:0];
     [cancelButton setTitleColor:[UIColor colorWithRed:118/255.0 green:118/255.0 blue:118/255.0 alpha:1] forState:0];
    [cancelButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [cancelButton addTarget:self action:@selector(_cancelAction) forControlEvents:UIControlEventTouchUpInside];
    [updateView addSubview:cancelButton];
    
    //更新按钮
    UIButton *updateButton = [UIButton buttonWithType:0];
    updateButton.frame = CGRectMake(CGRectGetMaxX(verticalityLine.frame), CGRectGetMaxY(horizontalLine.frame), cancelButton.frame.size.width, Ratio(50));
    [updateButton setTitleColor:[UIColor colorWithRed:109/255.0 green:190/255.0 blue:47/255.0 alpha:1] forState:0];
    [updateButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [updateButton addTarget:self action:@selector(_updateVersion) forControlEvents:UIControlEventTouchUpInside];
    [updateButton setTitle:JMLocalStr(@"立即更新") forState:UIControlStateNormal];
    [updateView addSubview:updateButton];
    
     [self _showWithAlert:bgView];
}
/** 更新按钮点击事件 跳转AppStore更新 */
- (void)_updateVersion
{
    
//    NSString *str = [NSString stringWithFormat:@"http://itunes.apple.com/us/app/id%@", APP_ID];
//    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}

/** 取消按钮点击事件 */
- (void)_cancelAction
{
    [self _dismissAlert];
}

/**
 添加Alert入场动画
 @param alert 添加动画的View
 */
- (void)_showWithAlert:(UIView*)alert{
    
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = AnimationTimeInterval;
    
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    animation.values = values;
    [alert.layer addAnimation:animation forKey:nil];
}


/** 添加Alert出场动画 */
- (void)_dismissAlert{
    
    [UIView animateWithDuration:AnimationTimeInterval animations:^{
        self.transform = (CGAffineTransformMakeScale(1.5, 1.5));
        self.backgroundColor = [UIColor clearColor];
        self.alpha = 0;
    }completion:^(BOOL finished) {
        [self removeFromSuperview];
    } ];
    
}

/**
 计算字符串高度
 @param string 字符串
 @param font 字体大小
 @param maxSize 最大Size
 @return 计算得到的Size
 */
- (CGSize)_sizeofString:(NSString *)string font:(UIFont *)font maxSize:(CGSize)maxSize
{
    return [string boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil].size;
}

@end
